from JDjango.api import model_type_data
from ..common import *

def create_empty_model(model_name: str, path: str) -> None:
    '''创建空模型'''
    verbose = model_name.lower().replace('_', ' ')
    template = f"""
class {model_name}(models.Model):
    
    class Meta:
        verbose_name = '{verbose}'
        verbose_name_plural = '{verbose}s'
"""
    append_file_whole(path, template)


def insert_field_into_model(model_path: str, model_name: str, field_code: str) -> bool:
    """向模型插入一行字段"""
    '''
        在本模型中，找到最后一个疑似的字段，如果没有则找Meta选项，
        若有Meta选项，则插在 Meta选项正上方，
        如果没有Meta选项，则找有没有定义函数，
        若有函数，则插在第一个函数上方，以上情况没有则默认插模型最后

        原则：按上面的逻辑，只要匹配一项，即插入退出
        False 的情况暂时不考虑，无非就是出现异常。目前只考虑成功，完全返回 True。
    '''
    types = model_type_data.read_field_types()
    # 获取模型文件中的模型代码段
    model_content: str = djangotools.models.cut_model_content_from_file(model_path, model_name)
    model_content_list: List[str] = model_content.split('\n')

    # 寻找最后一个疑似字段【倒序查找】只会查找注册过的字段类型
    len_model_content_list = len(model_content_list) - 1
    index = -1
    for i, line in enumerate(model_content_list[::-1]): # 倒序效率可能高一点
        matchs = [_ for _ in retools.PATT_MAYBE_FIELD_TYPE_NAME.findall(line) if _ in types]
        if len(matchs) > 0:
            index = len_model_content_list - i
            break
    if -1 != index: # 存在字段，插
        model_content_list.insert(index + 1, field_code) # 后插
        write_file(model_path, read_file(model_path).replace(model_content, '\n'.join(model_content_list)))
        return True

    # 寻找 Meta 选项 和 def 选项，谁先找到，就以谁为标准
    for i, _ in enumerate(model_content_list):
        if retools.PATT_META.match(_) or retools.PATT_FUNC_IN_CLASS.match(_):
            '''直接插，插完退出'''
            model_content_list.insert(i, field_code) # 前插
            write_file(model_path, read_file(model_path).replace(model_content, '\n'.join(model_content_list)))
            return True

    # 上述情况都没有时，直接插入尾部
    model_content_list.append(field_code) # 尾插
    write_file(model_path, read_file(model_path).replace(model_content, '\n'.join(model_content_list)))
    return True


def insert_option_into_meta(model_path: str, model_name: str, options: List[str]):
    """向meta选项插入一段选项"""
    '''
        先检测模型中是否存在 Meta 选项
        如果没有Meta选项，则新增

        options: 选项集的列表
    '''
    model_content: str = djangotools.models.cut_model_content_from_file(model_path, model_name)
    model_content_list: List[str] = model_content.split('\n')

    meta_index = -1
    for i, _ in enumerate(model_content_list):
        if retools.PATT_META.match(_):
            meta_index = i # 仅索引，行需要 + 1
            break
    
    if -1 == meta_index:
        '''没找到，新增'''
        verbose = model_name.lower().replace('_', ' ')
        space = '        '
        template_meta = f"""
    class Meta:
        verbose_name = '{verbose}'
        verbose_name_plural = '{verbose}s'
"""
        model_content_list.extend(template_meta.split('\n'))
        write_file(model_path, read_file(model_path).replace(model_content, '\n'.join(model_content_list)))
    else:
        '''
            坚持原则：无则插，有则改
        '''
        model_content_list.insert(meta_index+1, '\n'.join([f'        {_}' for _ in options]))
        write_file(model_path, read_file(model_path).replace(model_content, '\n'.join(model_content_list)))
